import UIKit
import FMDB

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    private let tableView = UITableView()
    private let memoryManager = MemoryManager.shared
    private let fileManager = FileStorageManager.self // 类方法调用
    
    // MARK: - 数据初始化（带实际功能的操作）
    private lazy var sections: [ListSection] = [
        // 内存分区
        ListSection(
            title: "内存管理",
            items: [
                ListData(
                    icon: "doc.text",
                    title: "全局变量",
                    description: "程序运行期间全局作用域的内存存储",
                    action: { [weak self] in
                        self?.showAlert(
                            title: "全局变量",
                            message: globalVariable // 直接访问全局变量
                        )
                    }
                ),
                ListData(
                    icon: "bolt",
                    title: "静态变量",
                    description: "存储在静态存储区，生命周期随程序运行",
                    action: { [weak self] in
                        self?.showAlert(
                            title: "静态变量",
                            message: MemoryManager.staticVariable // 访问类静态变量
                        )
                    }
                ),
                ListData(
                    icon: "person",
                    title: "单例对象",
                    description: "全局唯一实例，常驻内存",
                    action: { [weak self] in
                        self?.showAlert(
                            title: "单例对象",
                            message: "单例实例地址：\(String(describing: self?.memoryManager))"
                        )
                    }
                ),
                ListData(
                    icon: "square.and.arrow.down",
                    title: "控制器",
                    description: "控制器演示",
                    action: { [weak self] in
                        let vc = UserDefaultsViewController()
                        self?.present(vc, animated: true)
                    },
                )
            ]
        ),
        
        // 文件存储分区
        ListSection(
            title: "文件存储",
            items: [
                ListData(
                    icon: "gear",
                    title: "UserDefaults",
                    description: "轻量级键值对存储",
                    action: { [weak self] in
                        // 演示 UserDefaults 操作
                        self?.fileManager.saveToUserDefaults(key: "testKey", value: "UserDefaults 示例")
                        if let userValue = self?.fileManager.getFromUserDefaults(key: "testKey") {
                            self?.showAlert(
                                title: "UserDefaults",
                                message: "读取结果：\(userValue)"
                            )
                        }
                    }
                ),
                ListData(
                    icon: "doc",
                    title: "文件存储",
                    description: "直接操作文件系统（文档目录）",
                    action: { [weak self] in
                        // 演示文件存储操作
                        let testData = "文件存储示例数据"
                        do {
                            try self?.fileManager.saveToFile(data: testData, fileName: "test.txt")
                            if let fileValue = self?.fileManager.readFromFile(fileName: "test.txt") {
                                self?.showAlert(
                                    title: "文件存储",
                                    message: "读取结果：\(fileValue)"
                                )
                            }
                        } catch {
                            self?.showAlert(title: "错误", message: "文件操作失败：\(error.localizedDescription)")
                        }
                    }
                ),
                ListData(
                    icon: "database",
                    title: "SQLite",
                    description: "轻量级关系型数据库（需 FMDB 库）",
                    action: {
                        FileStorageManager.operateSQLite() // 调用 SQLite 示例代码
                        // 注：需先安装 FMDB 库并处理依赖
                    }
                ),
                ListData(
                    icon: "slider.horizontal.3",
                    title: "Core Data",
                    description: "苹果官方数据持久化框架",
                    action: {
//                        FileStorageManager.operateCoreData() // 调用 Core Data 示例代码
                        // 注：需在项目中配置 Core Data 模型
                    }
                )
            ]
        )
    ]
    
    deinit {
        
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "数据存储学习"
        setupUI()
        setupTableView()
        
        let a = UILabel()
        view.addSubview(a)
    }
    
    // MARK: - UI 配置
    private func setupUI() {
        view.backgroundColor = .white
        view.addSubview(tableView)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        NSLayoutConstraint.activate([
            tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
            tableView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
        ])
    }
    
    private func setupTableView() {
        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.rowHeight = 80
        tableView.sectionHeaderHeight = 44
    }
    
    // MARK: - UITableViewDataSource
    func numberOfSections(in tableView: UITableView) -> Int {
        return sections.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].items.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        let item = sections[indexPath.section].items[indexPath.row]
        
        // 配置系统图标
        if let systemImage = UIImage(systemName: item.icon) {
            let renderedImage = systemImage.withRenderingMode(.alwaysTemplate)
            cell.imageView?.image = renderedImage
            cell.imageView?.tintColor = .systemBlue
        } else {
            cell.imageView?.image = UIImage(systemName: "questionmark.circle")
            cell.imageView?.tintColor = .systemRed
        }
        
        // 配置文字
        cell.textLabel?.text = item.title
        cell.textLabel?.font = .systemFont(ofSize: 16, weight: .medium)
        cell.detailTextLabel?.text = item.description
        cell.detailTextLabel?.textColor = .secondaryLabel
        
        return cell
    }
    
    // MARK: - UITableViewDelegate
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return sections[section].title
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        sections[indexPath.section].items[indexPath.row].action()
    }
    
    // MARK: - 弹窗方法
    private func showAlert(title: String, message: String = "") {
        let alert = UIAlertController(
            title: title,
            message: message.isEmpty ? "点击查看 \(title) 详情" : message,
            preferredStyle: .alert
        )
        alert.addAction(UIAlertAction(title: "确定", style: .cancel))
        present(alert, animated: true)
    }
}
